package cn.com.base.sys.util;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;

public class Cache {
	static CacheManager cacheManager;
	
	static{
		cacheManager = CacheManager.create(Cache.class.getResourceAsStream("/ehcache.xml"));
	}
	
	
	private net.sf.ehcache.Cache cache;
	
	public static Cache getInstance(String name){
		return new Cache(getCache(name));
	}
	
	
	private Cache(net.sf.ehcache.Cache cache){
		this.cache=cache;
	}
	
	private static synchronized net.sf.ehcache.Cache getCache(String cacheName){
		net.sf.ehcache.Cache cache=cacheManager.getCache(cacheName);
		if(cache==null){
			net.sf.ehcache.Cache serviceCache= cacheManager.getCache("serviceCache");
			CacheConfiguration cfg=serviceCache.getCacheConfiguration().clone();
			cfg.setName(cacheName);
			cache=new net.sf.ehcache.Cache(cfg);
			cacheManager.addCache(cache);
		}
		return cache;
	}
	
	public synchronized void cacheValue(Object key,Object value){
		 net.sf.ehcache.Element element=new net.sf.ehcache.Element(key, value);
		 this.cache.put(element);
	}
	
	public synchronized <T> T getValue(Object key,T t){
		net.sf.ehcache.Element element=this.cache.get(key);
		if(element!=null){
			return (T)element.getObjectValue();
		}
		return null;
	}
	
	public synchronized Object getValue(Object key){
		net.sf.ehcache.Element element=this.cache.get(key);
		if(element!=null){
			return element.getObjectValue();
		}
		return null;
	}
	
	public void clear(){
		this.cache.removeAll();
	}
	
	
	public void remove(Object key){
		this.cache.remove(key);
	}

}
